package com.elitel.frame.main.config.serviceaccess.interceptor;

import com.elitel.frame.base.service.SysPrjServiceService;
import com.elitel.frame.core.util.ApplicationContextHelper;
import com.elitel.frame.main.config.serviceaccess.util.ServiceAccessPrintWriterUtil;
import com.elitel.frame.main.config.serviceaccess.util.ServiceAccessResponseStatus;
import com.elitel.frame.main.dao.AcAppMapper;
import com.elitel.frame.main.entity.AcApp;
import com.elitel.frame.main.entity.SysPrjservice;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.elitel.common.core.constant.RequestConstant.APP_CODE;
import static com.elitel.common.core.constant.RequestConstant.SERVICE_ID;

/**
 * 服务通用限制拦截器
 *
 * @author hi_bj
 * @since 2023-10-26
 */
public class GeneralInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String serviceCode = request.getParameter(SERVICE_ID);
        if (ObjectUtils.isEmpty(serviceCode)) {
            ServiceAccessPrintWriterUtil.write(response, ServiceAccessResponseStatus.ILLEGAL_SERVICE_ID.initValue());
            return false;
        }
        String appCode = request.getParameter(APP_CODE);
        if (ObjectUtils.isEmpty(appCode)) {
            ServiceAccessPrintWriterUtil.write(response, ServiceAccessResponseStatus.ILLEGAL_APP_CODE.initValue());
            return false;
        }
        //获取服务基础信息
        SysPrjServiceService sysPrjServiceService = ApplicationContextHelper.getApplicationContext().getBean(SysPrjServiceService.class);
        SysPrjservice sysPrjservice = sysPrjServiceService.getSysPrjserviceByServiceCode(serviceCode);
        if (ObjectUtils.isEmpty(sysPrjservice)) {
            ServiceAccessPrintWriterUtil.write(response, ServiceAccessResponseStatus.ILLEGAL_SERVICE_ID.initValue());
            return false;
        }
        //获取访问控制-应用基础信息
        AcAppMapper acAppMapper = ApplicationContextHelper.getApplicationContext().getBean(AcAppMapper.class);
        AcApp acApp = acAppMapper.selectByAppCode(appCode);
        if (ObjectUtils.isEmpty(acApp)) {
            ServiceAccessPrintWriterUtil.write(response, ServiceAccessResponseStatus.ILLEGAL_APP_CODE.initValue());
            return false;
        }
        return true;
    }
}

